﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using HtmlAgilityPack;
using CoursePack;

namespace WindowsFormsApplication2
{
    public partial class AddCourse : Form
    {
        private Course m_Course;

        public AddCourse(Course _Course)
        {
            InitializeComponent();
            this.m_Course = _Course;
            this.txtCourseName.Text = _Course.CourseName;
            this.txtCourseNumber.Text = _Course.CourseNumber;
            this.txtStartTime.Text = _Course.StartTime.ToString();
            this.txtFinishTime.Text = _Course.EndTime.ToString();
            this.txtMainSec.Text = _Course.Lecture.Section;

            if (_Course.Tutorial.Section != "")
            {
                this.txtRelSec1.Text = _Course.Tutorial.Section;
                this.txtDays.Text = _Course.Tutorial.Days;
            }
            else
                this.txtRelSec1.Text = "++";

            if (_Course.Lab.Section != "")
                this.txtRelSec2.Text = _Course.Lab.Section;
            else
                this.txtRelSec2.Text = "++";


            //this.txtSession.Text = _Course..ToString();
            this.txtCampus.Text = _Course.Campus;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // First request, we login to MyConcordia Portal
            HttpRequest MyConcordiaLogin = new HttpRequest(HttpMethod.POST, new Uri("https://my.concordia.ca/psp/portprod/?cmd=login&languageCd=ENG"),
                "https://www.myconcordia.ca/",
                "my.concordia.ca",
                new CookieContainer());

            this.lblStatus.Text = "Connecting to MyConcordia Portal";
            this.Refresh();

            MyConcordiaLogin.SendRequest("userid=&pwd=&GO=Sign+in&httpPort=&timezoneOffset=300&portal_pwd=");
   

            //Second request, we start a get a token to start the Registration session
            HttpRequest RegistrationPage = new HttpRequest(HttpMethod.GET, new Uri(" https://my.concordia.ca/psc/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?PORTALPARAM_PTCNAV=CU_WEBREG1&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_REGISTRATION&EOPP.SCLabel=Registration&EOPP.SCPTfname=CU_REGISTRATION&FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false&PortalActualURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1&PortalContentURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1&PortalContentProvider=EMPL&PortalCRefLabel=Undergraduate%20Registration&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fmy.concordia.ca%2fpsp%2fportprod%2f&PortalURI=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2f&PortalHostNode=EMPL&NoCrumbs=yes"),
                 "https://my.concordia.ca/psp/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?PORTALPARAM_PTCNAV=CU_WEBREG1&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_REGISTRATION&EOPP.SCLabel=Registration&EOPP.SCPTfname=CU_REGISTRATION&FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false",
                 "my.concordia.ca",
                 MyConcordiaLogin.Cookies);

            this.lblStatus.Text = "Openning registration session...";
            this.Refresh();

            HttpWebResponse RegistrationPageResponse = RegistrationPage.SendRequest();
      


            // Third request, we start the real session registration page
            HttpRequest RegistrationSessionStart = new HttpRequest(HttpMethod.GET, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr150.asp" + RegistrationPageResponse.ResponseUri.Query),
                "https://my.concordia.ca/psp/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder",
                "regsis.concordia.ca",
                RegistrationPage.Cookies);


            RegistrationSessionStart.SendRequest();
            string id = this.ExtractId(RegistrationSessionStart.ResponseStream);


            // Fourth request, we go to the record page
            HttpRequest RecordPage = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr200.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr150.asp" + RegistrationSessionStart.ResponseQuery,
                "regsis.concordia.ca",
                RegistrationSessionStart.Cookies);


            RecordPage.SendRequest(id);
            string id2 = this.ExtractId2(RecordPage.ResponseStream);
            



            // Fifth request, we add one class
            HttpRequest AddCoursePage = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr215.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr200.asp",
                "regsis.concordia.ca",
                RecordPage.Cookies);

            this.lblStatus.Text = "Adding the specified course to your list ...";
            this.Refresh();
            AddCoursePage.SendRequest("Id=" + id2 + "&language=1");
            


            // Sixth request, we add one class
            HttpRequest Gabadou = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr220.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr215.asp",
                "regsis.concordia.ca",
                AddCoursePage.Cookies);
            string data = "InputCourName=" + this.txtCourseName.Text + "&InputCourNum=" + this.txtCourseNumber.Text + "&InputCourSes=" + this.txtSession.Text + "&InputCourSec=&coursub=Submit&selectoption=S&Id=" + id2 + "&language=1";

            Gabadou.SendRequest(data);
          

            string title = System.Net.WebUtility.UrlEncode(this.ExtractCourseTitle(Gabadou.ResponseStream));



            // Sixth request, we add one class
            HttpRequest Confirmation = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr225.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr220.asp",
                "regsis.concordia.ca",
                Gabadou.Cookies);
            data = "CourName=" + this.txtCourseName.Text + "&CourNo=" + this.txtCourseNumber.Text + "+&Sess=" + this.txtSession.Text + "&MainSec=" + this.txtMainSec.Text + "&RelSec1=" + this.txtRelSec1.Text + "&RelSec2=" + this.txtRelSec2.Text + "&CatNum=" + this.textBox2.Text + "&Start=" + this.txtStartTime.Text + "&Finish=" + this.txtFinishTime.Text + "&Days=" + this.txtDays.Text + "&Campus=" + this.txtCampus.Text + "&Title=" + title + "&Id=" + id2 + "&language=1";

            Confirmation.SendRequest(data);
          
            // Seventh request, we add one class
            HttpRequest AddCourseForReal = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr300.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr225.asp",
                "regsis.concordia.ca",
                Confirmation.Cookies);
            string lol = "cournam=" + this.txtCourseName.Text
                + "&courno=" + this.txtCourseNumber.Text
                + "+&acyear=2012&session=" + this.txtSession.Text
                + "&mainsec=" + this.txtMainSec.Text
                + "&relsec1=" + this.txtRelSec1.Text
                + "&relsec2=" + this.txtRelSec2.Text
                + "&subses=++&catalog=" + this.textBox2.Text
                + "&Id=" + id2
                + "&language=1";

            this.lblStatus.Text = "Confirming your course request";
            this.Refresh();

            AddCourseForReal.SendRequest(lol);
           
            bool error = false;
            string errorTxt = "";
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(AddCourseForReal.ResponseStream);

            foreach (HtmlNode input in htmlDoc.DocumentNode.SelectNodes("//font"))
            {

                if (input.InnerHtml.Contains("Reason:"))
                {
                    error = true;
                    errorTxt = input.InnerHtml;
                    break;
                }
            }

            if (error)
            {
          
                this.lblStatus.ForeColor = Color.Red;
                this.lblStatus.Text = "Course Registration Denied";
                this.richTextBox1.Text = errorTxt;
                this.Refresh();

            }
            else
            {
                this.lblStatus.ForeColor = Color.Green;
                this.lblStatus.Text = "Course Registration Succeeded";
                this.Refresh();
            }
        }

        private string ExtractCourseTitle(string _Document)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(_Document);
            foreach (HtmlNode input in htmlDoc.DocumentNode.SelectNodes("//input"))
            {

                if (input.Attributes[1].Value == "Title")
                    return input.Attributes[2].Value;


            }
            return null;
        }

        private string ExtractId(string _Document)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(_Document);
            HtmlNode secondForm = htmlDoc.GetElementbyId("form2");
            HtmlNode id = secondForm.NextSibling.NextSibling;
            HtmlNode currYear = id.NextSibling.NextSibling;
            HtmlNode currSess = currYear.NextSibling.NextSibling;

            string strid = id.Attributes[2].Value;
            string strcurrYear = currYear.Attributes[2].Value;
            string strcurrSess = currSess.Attributes[2].Value;

            return "Id=" + strid + "&CurrYear=" + strcurrYear + "&CurrSess=" + strcurrSess + "&language=1&Continue=Continue";
        }

        private string ExtractId2(string _Document)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(_Document);
            HtmlNode secondForm = htmlDoc.GetElementbyId("form2");
            HtmlNode id = secondForm.NextSibling.NextSibling;

            string strid = id.Attributes[2].Value;

            return strid;
        }

        private string ExtractId3(string _Document)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(_Document);
            HtmlNode secondForm = htmlDoc.GetElementbyId("form3");
            HtmlNode id = secondForm.NextSibling.NextSibling;

            string strid = id.Attributes[2].Value;

            return strid;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // First request, we login to MyConcordia Portal
            HttpRequest MyConcordiaLogin = new HttpRequest(HttpMethod.POST, new Uri("https://my.concordia.ca/psp/portprod/?cmd=login&languageCd=ENG"),
                "https://www.myconcordia.ca/",
                "my.concordia.ca",
                new CookieContainer());

            this.lblStatus.Text = "Connecting to MyConcordia Portal";
            this.Refresh();

            MyConcordiaLogin.SendRequest("userid=&pwd=&GO=Sign+in&httpPort=&timezoneOffset=300&portal_pwd=");
      


            //Second request, we start a get a token to start the Registration session
            HttpRequest RegistrationPage = new HttpRequest(HttpMethod.GET, new Uri(" https://my.concordia.ca/psc/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?PORTALPARAM_PTCNAV=CU_WEBREG1&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_REGISTRATION&EOPP.SCLabel=Registration&EOPP.SCPTfname=CU_REGISTRATION&FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false&PortalActualURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1&PortalContentURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1&PortalContentProvider=EMPL&PortalCRefLabel=Undergraduate%20Registration&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fmy.concordia.ca%2fpsp%2fportprod%2f&PortalURI=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2f&PortalHostNode=EMPL&NoCrumbs=yes"),
                 "https://my.concordia.ca/psp/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?PORTALPARAM_PTCNAV=CU_WEBREG1&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_REGISTRATION&EOPP.SCLabel=Registration&EOPP.SCPTfname=CU_REGISTRATION&FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false",
                 "my.concordia.ca",
                 MyConcordiaLogin.Cookies);

            this.lblStatus.Text = "Openning registration session...";
            this.Refresh();

            HttpWebResponse RegistrationPageResponse = RegistrationPage.SendRequest();
        

            // Third request, we start the real session registration page
            HttpRequest RegistrationSessionStart = new HttpRequest(HttpMethod.GET, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr150.asp" + RegistrationPageResponse.ResponseUri.Query),
                "https://my.concordia.ca/psp/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_SIS_INFO.FieldFormula.IScript_WebReg1?FolderPath=PORTAL_ROOT_OBJECT.CU_REGISTRATION.CU_WEBREG1&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder",
                "regsis.concordia.ca",
                RegistrationPage.Cookies);

            this.lblStatus.Text = "Registration session opened...";
            this.Refresh();

            RegistrationSessionStart.SendRequest();
            string id = this.ExtractId(RegistrationSessionStart.ResponseStream);


            // Fourth request, we go to the record page
            HttpRequest RecordPage = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr200.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr150.asp" + RegistrationSessionStart.ResponseQuery,
                "regsis.concordia.ca",
                RegistrationSessionStart.Cookies);

            this.lblStatus.Text = "Starting dropping procedures...";
            this.Refresh();
            RecordPage.SendRequest(id);
            string id3 = this.ExtractId3(RecordPage.ResponseStream);



            // Fourth request, we go to the record page
            HttpRequest DropPage = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr400.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr200.asp",
                "regsis.concordia.ca",
                RecordPage.Cookies);

            this.lblStatus.Text = "Dropping course...";
            this.Refresh();
            string lol = "Id=" + id3 + "&language=1&cournam=" + this.txtCourseName.Text + "&courno="  + this.txtCourseNumber.Text + "&mainsec=" + this.txtMainSec.Text + "&relsec1=&relsec2=&coursess=" + this.txtSession.Text + "&subses=&submit=Drop";
            DropPage.SendRequest(lol);





            // Fourth request, we go to the record page
            HttpRequest DropPageConfirm = new HttpRequest(HttpMethod.POST, new Uri("https://regsis.concordia.ca/portalRegora/undergraduate/wr410.asp"),
                "https://regsis.concordia.ca/portalRegora/undergraduate/wr400.asp",
                "regsis.concordia.ca",
                DropPage.Cookies);

            this.lblStatus.Text = "Confirmation dropping course...";
            this.Refresh();

            lol = "Id=" + id3 + "&language=1&cournam=" + this.txtCourseName.Text + "&courno=" + this.txtCourseNumber.Text + "&mainsec=" + this.txtMainSec.Text + "&relsec1=&relsec2=&coursess=" + this.txtSession.Text + "&subses=";
            DropPageConfirm.SendRequest(lol);


            bool error = true;
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(DropPageConfirm.ResponseStream);

            foreach (HtmlNode input in htmlDoc.DocumentNode.SelectNodes("//font"))
            {

                if (input.InnerHtml.Contains("You have successfully dropped"))
                {
                    error = false;
                    break;
                }
            }

            if (error)
            {

                this.lblStatus.ForeColor = Color.Red;
                this.lblStatus.Text = "Course not dropped";
                this.Refresh();

            }
            else
            {
                this.lblStatus.ForeColor = Color.Green;
                this.lblStatus.Text = "Course Dropped";
                this.Refresh();
            }
        }
    }
}
